<template>
  <BasicLayout>
    <template #wrapper>
      <search class="search-form" :is-init-data="true" :exporting="textName" :form-config="formConfig" @onSubmit="onSubmit" @onExportFile="handleExport" />
      <!-- <table-pagination
        class="table"
        :height="tableHeight"
        :loading="loading"
        :selection-show="true"
        :columns="columns"
        :page-size="pageSize"
        :total="count"
        :current-page="currentPage"
        :page-sizes="[20, 50, 100, 200]"
        :data="comEliminationItemList"
        border
      >
        <template slot="totalEliminatingCount" slot-scope="scope">
          <el-link type="primary" :underline="false" @click="handleShow(scope.item)">{{ scope.item.totalEliminatingCount }}</el-link>
        </template>
      </table-pagination> -->
      <select-table ref="select-table" class="table" :is-select="paramsObj.state!==128" :approval-status="'regionEliApprovalState'" :loading="loading" :columns="columns" :data="comEliminationItemList">
        <template slot="totalEliminatingCount" slot-scope="scope">
          <span v-if="scope.item.totalEliminatingCount===0">{{ scope.item.totalEliminatingCount }}</span>
          <el-link v-else type="primary" :underline="false" @click="handleShow(scope.item)">{{ scope.item.totalEliminatingCount }}</el-link>
        </template>
      </select-table>
      <el-button v-if="paramsObj.state!==128" :style="{'float': 'left', 'margin': '10px 0'}" @click="all">批量操作</el-button>
      <pagination :style="{'text-align': 'right', 'padding': '10px 0'}" :total="count" :page="currentPage" :page-sizes="[20, 50, 100, 200]" :limit="pageSize" @pagination="onPagination" />
      <approve :visible="dialogApproveVisible" :area="'region'" :ids="ids" :date="paramsObj.date" @close="dialogApproveVisible=false" @onApprove="onApprove" />
      <table-dialog title="商品入池详情" :columns="[{ prop: 'month', label: '月份' },{ prop: 'reason', label: '原因' }]" :data="eliminatingDetails" :visible="dialogTableVisible" @close="dialogTableVisible=false" />
    </template>
  </BasicLayout>
</template>
<script>
// import TablePagination from '@/components/common/TablePagination';
import Pagination from '@/components/common/Pagination';
import TableDialog from '../tableDialog';
import SelectTable from '../selectTable';
import { getComEliChecklist, exportComEliChecklist } from '@/api/replacementApi';
import { exportFile } from '@/utils/tools';
import config from './config';
import Search from '../search.vue';
import Approve from '../approve.vue';

export default {
  name: 'RegionDetail',
  components: {
    // TablePagination,
    Pagination,
    TableDialog,
    SelectTable,
    Search,
    Approve
  },
  inject: ['getTableHeight'],
  data() {
    return {
      formConfig: config.formConfig,
      columns: config.detailColumns,
      loading: false,
      comEliminationItemList: [],
      eliminatingDetails: [],
      count: 0,
      currentPage: 1,
      pageSize: 20,
      dialogApproveVisible: false,
      ids: [],
      formCopy: {}, // 拷贝点击查询的搜索条件
      textName: '',
      dialogTableVisible: false,
      paramsObj: JSON.parse(this.CryptoJS.AES.decrypt(this.$route.params.params, 'paramsObj').toString(this.CryptoJS.enc.Utf8))
    };
  },
  computed: {
    tableHeight() {
      return this.getTableHeight();
    }
  },
  mounted() {},
  methods: {
    // 获取商品汰换清单
    onGetComEliChecklist({ page = 1, limit = 20 }, form = {}) {
      this.formCopy = JSON.parse(JSON.stringify(form));
      this.loading = true;
      this.currentPage = page;
      this.pageSize = limit;
      this.comEliminationItemList = [];
      getComEliChecklist({
        regions: [this.paramsObj.id],
        date: this.paramsObj.date,
        eliReportMode: 'REGION',
        pageNo: page,
        pageSize: limit,
        ...form,
        commodityCodes: form['commodityCodes'] ? [form['commodityCodes']] : null,
        commodityNames: form['commodityNames'] ? [form['commodityNames']] : null
      }).then(({ data }) => {
        this.loading = false;
        this.comEliminationItemList = data.comEliminationItemList;
        if (this.currentPage === 1) { this.count = data.count; }
      }).catch(() => {
        this.loading = false;
      });
    },
    // 搜索栏点击查询
    onSubmit(form) {
      this.onGetComEliChecklist({ page: 1, limit: this.pageSize }, form);
    },
    // 分页点击查询
    onPagination({ page, limit }) {
      this.onGetComEliChecklist({ page, limit }, this.formCopy);
    },
    // 审批成功
    onApprove() {
      this.onGetComEliChecklist({ page: this.currentPage, limit: this.pageSize }, this.formCopy);
    },
    // 批量操作列表数据
    all() {
      const ids = this.$refs['select-table'].getCheckboxRecords();
      if (ids.length < 1) {
        this.$message.warning('请勾选可选项再进行操作!');
        return;
      }
      this.ids = ids.map(item => item.id);
      this.dialogApproveVisible = true;
    },
    // 弹窗展示累计入池数列表信息
    handleShow(item) {
      this.dialogTableVisible = true;
      this.eliminatingDetails = item.eliminatingDetails.map(item => {
        const dateString = new Date(item.date);
        item.month = `${dateString.getFullYear()}年${dateString.getMonth() + 1}月`;
        return item;
      });
    },
    // 导出商品汰换清单
    handleExport({ name }) {
      this.textName = name;
      exportComEliChecklist({
        regions: [this.paramsObj.id],
        date: this.paramsObj.date,
        eliReportMode: 'REGION',
        ...this.formCopy,
        commodityCodes: this.formCopy['commodityCodes'] ? [this.formCopy['commodityCodes']] : null,
        commodityNames: this.formCopy['commodityNames'] ? [this.formCopy['commodityNames']] : null
      }).then(res => {
        this.blobDataJudgement(res, '大区版汰换清单.xlsx');
      }).catch(() => { this.textName = ''; });
    },
    // 二进制文件流返回错误判断
    blobDataJudgement(res, fileName) {
      if (res.type === 'application/json') {
        // 说明是普通对象数据，后台转换失败
        const reader = new FileReader();
        reader.readAsText(res, 'utf-8');
        reader.onload = () => {
          const jsonData = JSON.parse(reader.result);
          this.$message.error(jsonData.resultMessage);
        };
      } else {
        exportFile(res, fileName);
        this.$message.success('报表文件已生完毕, 下载中，请稍后');
      }
      this.textName = '';
    }
  }
};
</script>

